<template>
  <el-dialog :visible="dialogVisible" width="1300px" title="回收配置" @close="dialogVisible = false" top="80px">
    <div class="form-box bgf radius">
      <!-- <div class="tip">
        请选择你在回收页面希望用户进行填写的属性，如果要开启某个游戏的回收页面，请务必至少选择一项配置！
      </div> -->
      <div class=" flex ">
        <div class="infoBox" v-loading="loading">
          <div class="game-name-box">
            <div class="game-box flex ">
              <!-- <div class="game-item" :class="{ active: currentGame.id == game.id }" @click="gameClick(game)" v-for="(game, index) in allGameList" :key="index">
                {{ game.name }}
              </div> -->
            </div>
          </div>
          <div class="attr-box">
            <el-row>
              <el-col :span="12">
                <div class="input-attr">
                  <div class="flex" style="align-items:center">
                    <h3>选择游戏：</h3>
                    <el-select :disabled="isEdit" v-model="currentGameId" placeholder="请选择游戏" clearable filterable @change="gameClick">
                      <el-option v-for="item in allGameList" :key="item.id" :label="item.name" :value="item.id">
                      </el-option>
                    </el-select>

                  </div>
                </div>
                <div class="input-attr">
                  <div class="flex">
                    <h3>是否启用：<el-switch v-model="isHuishou" active-text="是" inactive-text="否" :active-value="1" :inactive-value="2">
                      </el-switch></h3>
                  </div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="input-attr">
                  <div class="flex">
                    <h3>游戏图标：</h3>
                    <uploadImageOne :showSaoma="false" v-model="currentGameIcon" @change="uploadSucccess"></uploadImageOne>
                  </div>
                </div>
              </el-col>
            </el-row>
            <div class="input-attr">
              <h3>输入框：</h3>
              <div class="flex attr-box-item">
                <div @click="attrClick(attr, index)" class="attr-item" :class="{ active: configObj[attr.id] ? true : false }" v-for="(attr, index) in attrInputAndNum" :key="index">{{ attr.fieldName }}</div>
              </div>
            </div>
            <div class="input-attr">
              <h3>单选框：</h3>
              <div class="flex attr-box-item">
                <div @click="attrClick(attr, index)" class="attr-item" :class="{ active: configObj[attr.id] ? true : false }" v-for="(attr, index) in attrRadio" :key="index">
                  {{
                    attr.fieldName }}</div>
              </div>
            </div>
            <div class="input-attr" v-if="attrCheckbox && attrCheckbox.length">
              <h3>多选框：</h3>
              <div class="attr-box-item checkbox-tit-box">
                <div class="attr-check-box flex">
                  <div v-for="(attr, index) in attrCheckbox" :key="index" @click="checkboxAttrClick(attr, index)" class="attr-item" :class="{ active: configObj[attr.id] || checkboxChildren.id == attr.id ? true : false }">
                    {{ attr.fieldName }}</div>

                </div>
              </div>
              <div class="attr-children-box flex">
                <div class="all-select">
                  <span @click="selectAll(checkboxChildren)" v-if="!checkboxChildren.selectAll">全选</span>
                  <span @click="selectAllCancel(checkboxChildren)" v-if="checkboxChildren.selectAll">全部取消</span>
                </div>
                <div @click="attrChildClick(checkboxChildren, childAttr)" class="attr-child-item" :class="{ active: configObj[checkboxChildren.id] && configObj[checkboxChildren.id].indexOf(childAttr.id) > -1 ? true : false }" v-for="(childAttr, index2) in checkboxChildren.childAttributes"
                     :key="index2">
                  {{ childAttr.fieldName }}</div>
              </div>
            </div>
            <div class="input-attr" v-if="attrboxRadio && attrboxRadio.length">
              <h3>多选>单选：</h3>
              <div class="attr-box-item checkbox-tit-box">
                <div class="attr-check-box flex">
                  <div v-for="(attr, index) in attrboxRadio" :key="index" @click="checkboxAttrClick(attr, index)" class="attr-item" :class="{ active: configObj[attr.id] || boxradioChildren.id == attr.id ? true : false }">
                    {{ attr.fieldName }}</div>

                </div>
              </div>
              <div class="attr-children-box flex">
                <div @click="attrChildClick(boxradioChildren, childAttr)" class="attr-child-item" :class="{ active: configObj[boxradioChildren.id] && configObj[boxradioChildren.id].indexOf(childAttr.id) > -1 ? true : false }" v-for="(childAttr, index2) in boxradioChildren.childAttributes"
                     :key="index2">
                  {{ childAttr.fieldName }}</div>
              </div>
            </div>
          </div>
          <div class="btns">
            <el-button plain type="primary" @click="close">取消</el-button>
            <el-button type="primary" @click="saveConfig">保存</el-button>
          </div>
        </div>
        <div class="inputBox">

          <div class="viewTit flex">
            <span>回收页面预览</span>
            <!-- <div style="margin-left:10px">
              <el-button type="primary" @click="copy" size="small">复制链接</el-button>
            </div> -->
          </div>

          <iframe v-if="reViewUrl" style="width: 100%;height: calc(100% - 50px);" :src="reViewUrl" ref="iframe1" frameborder="0"></iframe>
          <div style="color:#999;font-size:20px;text-align:center;line-height:100px;padding-top:100px">暂未选择游戏</div>
        </div>
      </div>

    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from "vuex";
import gameListApi from "@/api/gameConfig/gameList";
import gameConfigApi from "@/api/gameConfig";
import gujiaApi from "@/api/tenantApis/gujiaApi";
export default {
  name: "",
  data() {
    return {
      dialogVisible: false,
      loading: false,
      reViewUrl: "",
      title: "回收配置",
      allGameList: [],
      currentGame: {},
      currentGameId: "",
      currentGameIcon: "",
      attrs: [],
      attrInputAndNum: [],
      attrRadio: [],
      attrCheckbox: [],
      attrboxRadio: [],
      checkboxChildren: {}, //当前展示的多选项
      boxradioChildren: {}, //当前展示的多选>单选项
      isHuishou: 1,

      configObj: {}, //已选择的属性对象，key为选择的字段id，value为字段子级ids，input类型的value为true，，如果不在该对象里面，则字段没有被选中
      formData: [],
      reViewUrlBasic: "",
      reViewUrlNew: "",
      h5BasicUrl: "",

      shanghuAttrIds: [],
      isEdit: false,
    };
  },
  created() {
    // this.getH5BasicUrl();
  },
  computed: {
    ...mapGetters(["userInfo", "shopInfo"]),
  },
  methods: {
    // // 打开弹窗
    open(flag, gameId) {
      // console.log("%c Line:150 🍯 gameId", "color:#7f2b82", gameId);
      //console.log("%c Line:134 🍫 link", "color:#b03734", link);
      // this.reViewUrlBasic = link
      if (flag == "add") {
        this.attrInputAndNum = [];
        this.attrRadio = [];
        this.attrCheckbox = [];
        this.attrboxRadio = [];
        this.configObj = {};
        this.isEdit = false;
      } else {
        this.currentGameId = gameId;
        this.isEdit = true;
      }
      let str = "";
      if (this.shopInfo.domain) {
        str = this.shopInfo.domain;
        if (str.includes(",")) {
          str = str.split(",")[0];
        }
      }
      this.reViewUrlBasic =
        window.location.protocol +
        "//" +
        str +
        "/pages/retrieveAccount/jingjiahuishou/inputInfo";
      this.h5BasicUrl =
        window.location.protocol +
        "//" +
        str +
        "/pages/saleGameList/index?pageType=2&pageFrom=kefu";
      // 请求所有游戏和属性
      this.getGameList(gameId);
      this.dialogVisible = true;
    },
    // 上传图标成功
    uploadSucccess(e){
      this.currentGameIcon = e
    },
    // 复制回收链接
    copy() {
      this.$copyText(this.h5BasicUrl).then(() => {
        this.$message.success("已复制到剪切板");
      });
    },
    // 保存配置
    saveConfig() {
      let that = this;
      that.formData = [];
      if(!this.currentGameIcon){
        return this.$message.error("请上传游戏图标！");
      }
      // let attrIds = [];
      for (let key in this.configObj) {
        let item = that.configObj[key];
        //console.log(item) // foo, bar
        if (item === true) {
          // attrIds.push(key);
          that.formData.push({
            gameId: that.currentGame.id,
            tempId: key,
            attributeContent: null,
          });
        } else if (item && item.length) {
          // attrIds.push(key);
          // attrIds = attrIds.concat(item);
          that.formData.push({
            gameId: that.currentGame.id,
            tempId: key,
            attributeContent: item.join(","),
          });
        }
      }
      if (this.formData.length == 0 && this.isHuishou == 1) {
        return this.$message.error("请至少选择一项配置！");
      }
      this.loading = true;
      // //console.log("%c Line:118 🍧 this.formData", "color:#33a5ff", this.formData);
      // this.isHuishou = res.data.isEnableConfig
      gameConfigApi
        .editGameConfigList({
          configs: this.formData,
          gameId: that.currentGame.id,
          icon:this.currentGameIcon,
          isEnableConfig: this.isHuishou,
        })
        .then((res) => {
          this.loading = false;
          //console.log("%c Line:138 🍣 res", "color:#ed9ec7", res);
          if (res.code == 200) {
            this.$message.success("保存成功!");
            this.reloadView();
            this.$parent.getList();
          }
          // attrIds;
          // console.log("%c Line:192 🥕 attrIds", "color:#7f2b82", attrIds);
          if (this.shanghuAttrIds && this.shanghuAttrIds.length) {
            gujiaApi
              .tenantAttributeSettingsAdd({
                gameAttributeIds: this.shanghuAttrIds.join(","),
              })
              .then((res) => {
                // console.log("%c Line:197 🥐 res", "color:#ed9ec7", res);
              });
          }
        });
    },
    // 重新加在预览页面
    reloadView() {
      // 刷新预览
      this.reViewUrl = "";
      this.$nextTick(() => {
        setTimeout(() => {
          this.reViewUrl = this.reViewUrlNew;
        }, 1000);
      });
    },
    // 获取游戏列表
    getGameList(gameId) {
      gameListApi.getGameList().then((res) => {
        if (res.code == 200) {
          this.allGameList = res.rows;
          if (gameId) {
            this.gameClick(gameId);
          } else {
            // this.gameClick(res.rows[0]);
          }
        }
      });
    },
    // 获取选中游戏的属性字段
    // 获取游戏属性列表
    getAttrList() {
      let obj = {
        gameId: this.currentGame.id,
      };
      this.attrInputAndNum = [];
      this.attrRadio = [];
      this.attrCheckbox = [];
      this.attrboxRadio = [];
      this.configObj = {};
      this.loading = true;
      gameConfigApi.getGameConfigList(obj).then((res) => {
        this.loading = false;
        if (res.code == 200) {
          this.isHuishou = res.data.isEnableConfig;
          if (!this.isEdit) {
            this.isHuishou = 1;
          }
          if(res.data.icon){
            this.currentGameIcon = res.data.icon
          }
          this.attrs = res.data.configs;
          this.attrs.forEach((item) => {
            // if (item.isEnable == 0) {
            // 分类属性，回显选中状态
            // configObj
            if (item.isEnable === "0") {
              if (item.fieldType == "input" || item.fieldType == "number") {
                this.attrInputAndNum.push(item);
                if (item.isEnableConfig == 1) {
                  // 选中
                  this.configObj[item.id] = true;
                }
              } else if (item.fieldType == "checkbox") {
                this.attrCheckbox.push(item);
                if (item.isEnableConfig == 1) {
                  // 选中
                  this.configObj[item.id] = [];
                  item.childAttributes.forEach((r) => {
                    if (r.isEnableConfig == 1) {
                      this.configObj[item.id].push(r.id);
                      this.shanghuAttrIds.push(r.id);
                    }
                  });
                }
              } else if (item.fieldType == "radio") {
                this.attrRadio.push(item);
                if (item.isEnableConfig == 1) {
                  // 选中
                  this.configObj[item.id] = [];
                  item.childAttributes.forEach((r) => {
                    this.configObj[item.id].push(r.id);
                    this.shanghuAttrIds.push(r.id);
                  });
                }
              } else if (item.fieldType == "boxradio") {
                this.attrboxRadio.push(item);
                if (item.isEnableConfig == 1) {
                  // 选中
                  this.configObj[item.id] = [];
                  item.childAttributes.forEach((r) => {
                    if (r.isEnableConfig == 1) {
                      this.configObj[item.id].push(r.id);
                      r.childAttributes.forEach((r2) => {
                        this.shanghuAttrIds.push(r2.id);
                        // this.configObj[item.id].push(r2.id);
                      });
                    }
                  });
                }
              }
            }
          });
          if (this.attrCheckbox.length) {
            this.checkboxAttrClick(this.attrCheckbox[0]);
          }
          if (this.attrboxRadio.length) {
            this.checkboxAttrClick(this.attrboxRadio[0]);
          }
        }
      });
    },
    gameClick(id) {
      // console.log("%c Line:343 🥒 game", "color:#ffdd4d", id);
      if (id) {
        this.allGameList.forEach((r) => {
          if (r.id == id) {
            this.currentGame = r;
            this.getAttrList();
            if(this.currentGame.icon){
              this.currentGameIcon = this.currentGame.icon
            }
            let AU = "iPhone";
            // AU = encodeURIComponent(AU)
            // this.reViewUrlNew = `http://192.168.3.101/pages/retrieveAccount/jingjiahuishou/inputInfo?tenantId=${this.shopInfo.tenantId}&gameId=${this.currentGame.id}&gameName=${this.currentGame.name}`;
            this.reViewUrlNew = `https://yulan.yududs.com/pages/retrieveAccount/jingjiahuishou/inputInfo?tenantId=${this.shopInfo.tenantId}&gameId=${this.currentGame.id}&gameName=${this.currentGame.name}&gameType=${this.currentGame.type}`;
            this.reloadView();
          }
        });
      }
    },
    // 属性被点击
    attrClick(attr, index) {
      //console.log("%c Line:146 🍑 attr", "color:#2eafb0", attr);
      if (attr.fieldType == "input" || attr.fieldType == "number") {
        // 输入框
        if (this.configObj[attr.id]) {
          this.$set(this.configObj, attr.id, null);
        } else {
          this.$set(this.configObj, attr.id, true);
        }
      } else if (attr.fieldType == "radio") {
        if (this.configObj[attr.id]) {
          this.$set(this.configObj, attr.id, null);
          for (let i = 0; i < attr.childAttributes.length; i++) {
            let r = attr.childAttributes[i];
            if (this.shanghuAttrIds.includes(r.id)) {
              this.shanghuAttrIds.splice(this.shanghuAttrIds.indexOf(r.id), 1);
              i--;
            }
          }
        } else {
          let arr = [];
          attr.childAttributes.forEach((r) => {
            arr.push(r.id);
            this.shanghuAttrIds.push(r.id);
          });
          this.$set(this.configObj, attr.id, arr);
        }
      }
      this.$forceUpdate();

      // this.configObj
      //console.log("%c Line:163 🍐 this.configObj", "color:#465975", this.configObj);
    },
    // 多选项属性被点击
    checkboxAttrClick(attr) {
      if (attr.fieldType == "checkbox") {
        this.checkboxChildren = attr;
      }
      if (attr.fieldType == "boxradio") {
        this.boxradioChildren = attr;
      }
    },
    // 全选子属性
    selectAll(attr) {
      attr.selectAll = true;
      this.configObj[attr.id] = [];
      attr.childAttributes.forEach((r) => {
        this.configObj[attr.id].push(r.id);
        this.shanghuAttrIds.push(r.id);
      });
      this.$forceUpdate();
    },
    // 全部取消选择子属性
    selectAllCancel(attr) {
      attr.selectAll = false;
      delete this.configObj[attr.id];
      for (let i = 0; i < attr.childAttributes.length; i++) {
        let r = attr.childAttributes[i];
        if (this.shanghuAttrIds.includes(r.id)) {
          this.shanghuAttrIds.splice(this.shanghuAttrIds.indexOf(r.id), 1);
          i--;
        }
      }
      this.$forceUpdate();
    },
    // 子级属性被点击
    attrChildClick(attr, childAttr) {
      if (attr.fieldType == "checkbox" || attr.fieldType == "boxradio") {
        // 多选项点击子级属性
        // 判断选中对象中有没有当前父属性  如果没有，添加
        if (!this.configObj[attr.id]) {
          this.configObj[attr.id] = [];
        }
        // 判断该属性是否被选中
        if (
          this.configObj[attr.id] &&
          this.configObj[attr.id].indexOf(childAttr.id) > -1
        ) {
          // 已选中的属性，删除选中
          let i = this.configObj[attr.id].indexOf(childAttr.id);
          this.configObj[attr.id].splice(i, 1);
          // 如果没有属性了，删除该父级属性
          if (this.configObj[attr.id].length == 0) {
            delete this.configObj[attr.id];
          }

          // 处理 商家自定义属性价值 添加的属性IDs  删除
          if (attr.fieldType == "checkbox") {
            if (this.shanghuAttrIds.includes(childAttr.id)) {
              this.shanghuAttrIds.splice(
                this.shanghuAttrIds.indexOf(childAttr.id),
                1
              );
            }
          } else if (attr.fieldType == "boxradio") {
            // 原神类皮肤带二级选择项的
            if (childAttr.childAttributes && childAttr.childAttributes.length) {
              for (let i = 0; i < childAttr.childAttributes.length; i++) {
                let r = childAttr.childAttributes[i];
                // 已选中的属性，删除选中
                if (this.shanghuAttrIds.includes(r.id)) {
                  this.shanghuAttrIds.splice(
                    this.shanghuAttrIds.indexOf(r.id),
                    1
                  );
                  i--;
                }
              }
            }
          }
        } else {
          // 将属性添加到已选中
          this.configObj[attr.id].push(childAttr.id);
          // 处理 商家自定义属性价值 添加的属性IDs  添加
          if (attr.fieldType == "checkbox") {
            this.shanghuAttrIds.push(childAttr.id);
          } else if (attr.fieldType == "boxradio") {
            // 原神类皮肤带二级选择项的
            if (childAttr.childAttributes && childAttr.childAttributes.length) {
              for (let i = 0; i < childAttr.childAttributes.length; i++) {
                let r = childAttr.childAttributes[i];
                // 未选中  进行选中
                this.shanghuAttrIds.push(r.id);
              }
            }
          }
        }
      }
      this.$forceUpdate();
      // this.configObj
      //console.log("%c Line:205 🍡 this.configObj", "color:#ffdd4d", this.configObj);
    },
    close() {
      this.configObj = {};

      this.dialogVisible = false;
    },
  },
};
</script>
<style scoped lang="scss">
.form-box {
  padding: 20px;
  padding-top: 0;
}
.center {
  text-align: center;
}

.tip {
  color: crimson;
  font-size: 16px;
}

.infoBox {
  width: 800px;
  height: calc(100vh - 290px);
  overflow-y: auto;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 15px;

  .game-name-box {
    width: 100;
    overflow-x: auto;
    overflow-y: hidden;
    padding-bottom: 10px;
  }

  .game-box {
    width: auto;

    .game-item {
      flex-shrink: 0;
      margin-right: 15px;
      height: 36px;
      line-height: 36px;
      border: 1px solid #eee;
      padding: 0 10px;
      border-radius: 5px;
      cursor: pointer;

      &.active {
        color: #fff;
        background-color: #409eff;
      }
    }
  }

  .attr-box-item {
    flex-wrap: wrap;

    &.active {
      color: bule;
    }
  }

  .checkbox-tit-box {
    width: 100%;
    height: 52px;
    overflow-x: auto;
    overflow-y: hidden;
    margin-bottom: 10px;
  }

  .attr-item {
    margin-right: 10px;
    padding: 3px 10px;
    border-radius: 5px;
    border: 1px solid #eee;
    margin-bottom: 10px;
    cursor: pointer;
    flex-shrink: 0;

    &.active {
      color: #fff;
      background-color: #409eff;
    }
  }

  .attr-children-box {
    flex-wrap: wrap;
    border-radius: 10px;
    border: 1px solid #ddd;
    padding: 10px;

    .all-select {
      cursor: pointer;
      margin-right: 15px;
      color: #409eff;
      line-height: 26px;
    }
  }

  .attr-child-item {
    cursor: pointer;
    margin-right: 10px;
    padding: 1px 10px;
    border-radius: 5px;
    border: 1px solid #eee;
    margin-bottom: 10px;

    &.active {
      color: #fff;
      background-color: #409eff;
    }
  }
}

.inputBox {
  flex-shrink: 0;
  width: 405px;
  height: calc(100vh - 290px);
  margin-left: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 15px;
  position: relative;

  .viewTit {
    font-size: 18px;
    background: #fff;
    position: absolute;
    height: 45px;
    width: 350px;
    font-weight: bold;
    align-items: center;
  }
}

.btns {
  text-align: center;
  margin: 15px 0;
}
</style>
